package com.itrip.itriosearch.util;

import com.itrip.common.constants.ResultCodeEnum;
import com.itrip.common.exception.GuliException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JwtUtil {
    final static String base64EncodedSecretKey = "86686ed9-f8e8-4405-817b-4eb4037af840";

   public final static long TOKEN_EXP = 7200000; //过期时间，默认设置5分钟

    public static String getToken(String userName) {
        return Jwts.builder()
                .setSubject(userName)
                .claim("roles", "tester")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXP))
                .signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
                .compact();
    }

    /**
     * 检查token,只要不正确就会抛出异常
     */

    public static Claims checkToken(String token) throws SecurityException {
        try {
            final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
            return claims;
        } catch (ExpiredJwtException e1) {
            throw new GuliException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.USERUNLOGIN_ERROR);
        }
    }
}
